package com.tongcao.cn.netty.aio;

import com.tongcao.cn.netty.Io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author:tongcao
 * @since:2019/7/9 10:53
 * Description:
 * AIO, 也叫 NIO2.0 是一种异步非阻塞的通信方式
 * * NIO 通过多路复用器轮询注册的通道，从而实现非阻塞效果，同时也说明了NIO是同步的。既然AIO是非阻塞的，哪它又是如何实现异步非阻塞的呢？
 * * AIO 引入了异步通道的概念 AsynchronousServerSocketChannel 和 AsynchronousSocketChannel
 */
public class AioServer implements Io {


    private ExecutorService executorService;// 线程池
    private AsynchronousChannelGroup threadGroup;    // 通道组

    public AsynchronousServerSocketChannel asynchronousServerSocketChannel;// 服务器通道

    public void start(Integer port) {

        try {
            executorService = Executors.newCachedThreadPool();
            //
            threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);

            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open(threadGroup);

            asynchronousServerSocketChannel.bind(new InetSocketAddress(PORT));
            System.out.println("server start , port : " + port);
            // 5.等待客户端请求
            asynchronousServerSocketChannel.accept(this, new AioHandler());

            // 一直阻塞 不让服务器停止，真实环境是在tomcat下运行，所以不需要这行代码
            Thread.sleep(Integer.MAX_VALUE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static void main(String[] args) {
        final AioServer server = new AioServer();
        server.start(PORT);
    }
}